import mqtt from 'mqtt/dist/mqtt.js' //引入mqtt依赖

var client                          
let mqttConnected = false  //mqtt连接状态，这个可以不要，直接查询client.connected即可
const publishTopic = 'PERSONDEVICE/#'  //发布Topic
const MQTT_IP = 'mqtt.lwbj.net:8083/mqtt' //mqtt地址端口
const MQTT_OPTIONS = {
    connectTimeout: 5000,      //连接超时时间
    clientId: 'meter-yuanxibing',  //clientId不能重复，这里可以随机生成
    username: 'admin',         //用户名
    password: 'bl@2199110',         //密码
    clean: false        
}

//创建客户端连接
export function mqttConnect() {
	// #ifdef H5
	client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS,function(err){
		console.log(err)
	})
	// #endif
	// #ifdef MP-WEIXIN||APP-PLUS
	client = mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS,function(err){
		console.log(err)
	})
	// #endif

	client.on('connect', function() {
	    console.log('连接成功')
		mqttConnected = true
	}).on('reconnect', function(error) {
	    console.log('正在重连...', error)
		mqttConnected = false
	}).on('error', function(error) {
	    console.log('连接失败...', error)
		mqttConnected = false
	}).on('end', function() {
	    console.log('连接断开')
		mqttConnected = false
	}).on('close',function(){
		console.log('连接关闭')
		mqttConnected = false
	}).on('offline',function(){
		console.log('客户端下线')
	}).on('message', function (topic, message) {
  // message is Buffer
  console.log(topic)
  console.log(message.toString())
  //client.end()
})
}
//发布消息
export function mqttPublish(msg){
	if(mqttConnected){
		client.publish(publishTopic,msg,{qos:1,retain:false});//hello mqtt +
		console.log('发布了一条消息',msg)
	}else{
		uni.showToast({
			title: 'MQTT服务器未连接',
			icon: 'none'
		});
	}
}
//订阅消息
export function mqttSubscribe(topic) {
    if (mqttConnected) {
        client.subscribe(topic, { qos: 1 }, (err) => {
			console.log(err)
            if (!err) {
                console.log('订阅主题成功:', topic);
            } else {
                console.error('订阅主题失败:', err);
            } 
        });
    } else {
        uni.showToast({
            title: 'MQTT服务器未连接',
            icon: 'none'
        });
    }
}
//断开连接
export function mqttDisconnect(){
	console.log('mqttConnected',mqttConnected)
	console.log('client',client) 
	if(mqttConnected){
		client.end(true)
		mqttConnected = false
	}
	
}